from flask import render_template, request, jsonify, session, redirect, url_for, g
from werkzeug.security import generate_password_hash, check_password_hash

from models import db
from models.index import User
from views import passport_bp


@passport_bp.route('/register')
def register():
    user = g.user
    if user:
        return redirect(url_for('index.index'))
    return render_template('registered.html', shop_car_count=g.shop_car_count)


@passport_bp.route('/login')
def login():
    user = g.user
    if user:
        return redirect(url_for('index.index'))
    return render_template('Login.html', shop_car_count=g.shop_car_count)


@passport_bp.route('/register_verify', methods=['POST'])
def register_verify():
    user = g.user
    if user:
        return redirect(url_for('index.index'))
    phone = request.json.get('phone')
    nick_name = request.json.get('nick_name')
    password = request.json.get('password')
    user_db = db.session.query(User).filter(User.phone == phone).first()
    if user_db:
        ret = {
            'errno': 4001,
            'errmsg': '该手机号已经存在'
        }
        return jsonify(ret)
    user = User()
    try:
        user.phone = phone
        user.nick_name = nick_name
        user.password_hash = generate_password_hash(password)
        db.session.add(user)
        db.session.commit()
        session['user_id'] = user.id
        ret = {
            'errno': 0,
            'errmsg': '注册成功'
        }

    except Exception as e:
        ret = {
            'errno': 4002,
            'errmsg': '注册失败'
        }
    return jsonify(ret)


@passport_bp.route('/login_verify', methods=['POST'])
def login_verify():
    user = g.user
    if user:
        return redirect(url_for('index.index'))
    phone = request.json.get('username')
    password = request.json.get('password')
    user = db.session.query(User).filter(User.phone == phone).first()

    if user and check_password_hash(user.password_hash, password):
        session['user_id'] = user.id
        ret = {
            'errno': 0,
            'errmsg': '登录成功'
        }
    else:
        ret = {
            'errno': 4003,
            'errmsg': '用户名或密码错误'
        }

    return jsonify(ret)


@passport_bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index.index'))
